package com.example.campuslink.viewModel

import android.content.Intent
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.example.campuslink.commen.db.school.SchoolInfoTable
import com.example.campuslink.commen.db.userNumber.UserNumberTable
import com.example.campuslink.commen.enums.SchoolProvinceEnums
import com.example.campuslink.commen.tools.Sp
import com.example.campuslink.ui.activity.MainActivity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class SchoolChoiceViewModel: BaseViewModel() {
    private val _isAdmin = MutableLiveData<Boolean>(false)
    val isAdmin = _isAdmin
    private val _provinceIndex = MutableLiveData<Int>(0)
    val provinceIndex = _provinceIndex
    val provinceData =  SchoolProvinceEnums.chineseNames()
    private val _schoolLiveData = MutableLiveData<List<SchoolInfoTable>>()
    val schoolLiveData = _schoolLiveData
    fun haveSchool(){
        viewModelScope.launch(Dispatchers.IO) {
            val numberInfo = userNumberDao.getUserNumber(Sp.getString(context!!,"userNumber","")?:"")
            if (numberInfo != null && numberInfo.schoolName != "") {
                startActivity(Intent(),targetClass = MainActivity::class.java,true)
            }
        }
    }

    fun jumpToMainActivity(){
        startActivity(Intent(),targetClass = MainActivity::class.java,true)
    }

    fun deleteSchool(id : Int){
        viewModelScope.launch(Dispatchers.IO) {
            schoolInfoDao.deleteSchoolInfo(id)
            getProvinceSchool(provinceIndex.value?:0)
        }
    }

    fun addSchool(schoolName:String){
        viewModelScope.launch(Dispatchers.IO) {
            val number = userNumberDao.getUserNumber(Sp.getString(context,"userNumber","")?:"")
            val schoolInfo = schoolInfoDao.getSchoolInfoBySchoolName(schoolName)
            if(number!=null){
                userNumberDao.updateUserNumber(number.copy(schoolName = schoolName))
            }
            if(schoolInfo!=null){
                schoolInfo.schoolUser.add(number?.telNumber?:return@launch)
                schoolInfoDao.updateSchoolInfo(schoolInfo)
            }
        }
    }


    fun getProvinceSchool(index:Int){
        viewModelScope.launch(Dispatchers.IO) {
            if(index==0){
                _schoolLiveData.postValue(schoolInfoDao.getAllSchoolInfo())
            }else{
                _schoolLiveData.postValue(schoolInfoDao.getSchoolInfoByProvince(provinceData[index]))
            }
        }
    }
    fun setProvinceIndex(index: Int){
        _provinceIndex.value = index
    }

    fun isAdmin(){
        viewModelScope.launch(Dispatchers.IO) {
            val numberInfo = userNumberDao.getUserNumber(Sp.getString(context!!,"userNumber","")?:"")
            if (numberInfo?.telNumber == "admin") {
                viewModelScope.launch(Dispatchers.Main) {
                    _isAdmin.value = true
                }

            }
        }
    }
}